<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
        v-has="`btn.Trademark.add`"
        >添加品牌</el-button
      >
      <!-- 表格组件:用于展示已有的品牌数据 -->
      <el-table style="margin: 10px 0" border :data="trademarkArr">
        <!-- table:
        ---border: 带边框的表格 
        ---label:设置标题
        ---width:设置宽度
        ---align:设置对齐方式
      -->
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称">
          <template #="{ row, $index }">
            <span style="color: brown">{{ row.tmName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>
            <el-popconfirm
              :title="`确定删除${row.tmName}吗?`"
              width="250px"
              icon="Delete"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 
      current-page / v-model:current-page:当前页码 
      page-size:设置每一页展示数据的条数
      page-sizes:设置下拉菜单的数据
      background:设置分页器按钮的背景
      layout:设置分页器六个子组件的布局
    -->
      <el-pagination
        @current-change="getHasTrademark"
        @size-change="getHasTrademark()"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <!-- 对话框组件:添加品牌 
      v-model:控制对话框的显示与隐藏 
      title:设置对话框左上角的标题
    -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      width="500"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- action:上传图片的接口地址
               show-file-list:展示上传进度条  
          -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :headers="headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽:footer -->
      <template #footer>
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import type {
  Trademark,
  Records,
  TrademarkResponseData,
} from "@/api/product/trademark/type";
import type { UploadProps } from "element-plus";
import { ElMessage } from "element-plus";
import request from "@/utils/request";

// el-upload 上传 http 请求头，携带 Token
// 引入用户相关的仓库
import useUserStore from "@/store/modules/user";
// 获取用户相关的小仓库：获取仓库内部token，登录成功以后携带给服务器
const userStore = useUserStore();
const headers = { Token: userStore.token };

// 当前页码
const pageNo = ref<number>(1);
// 每一页展示多少条数据
const limit = ref<number>(5);

// 存储已有品牌数据总数
const total = ref<number>(0);
// 存储已有品牌数据
const trademarkArr = ref<Records>([]);
// 控制对话框的显示与隐藏
const dialogFormVisible = ref<boolean>(false);
// 定义收集新增品牌数据
const trademarkParams = reactive<Trademark>({
  tmName: "",
  logoUrl: "",
});
// 获取表单组件实例
const formRef = ref<any>();
// 封装请求品牌数据的方法
const getHasTrademark = async (paper = 1) => {
  pageNo.value = paper;
  const res: TrademarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value
  );

  if (res.code === 200) {
    // 存储已有品牌的总个数
    total.value = res.data.total;
    trademarkArr.value = res.data.records;
    trademarkArr.value.forEach(async (item: any) => {
      const resImg = await request.get("https://v2.xxapi.cn/api/heisi");
      item.logoUrl = resImg.data;
    });
  }
};

// 组件挂载完毕请求数据
onMounted(() => {
  getHasTrademark();
});

// 添加品牌按钮回调
const addTrademark = () => {
  // 重置表单
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  trademarkParams.id = 0;
  nextTick(() => {
    formRef.value.clearValidate("logoUrl");
    formRef.value.clearValidate("tmName");
  });
  dialogFormVisible.value = true;
};

// 修改品牌按钮回调
// row :当前行数据
const updateTrademark = (row: Trademark) => {
  nextTick(() => {
    formRef.value.clearValidate("logoUrl");
    formRef.value.clearValidate("tmName");
  });
  // 回传数据
  trademarkParams.tmName = row.tmName;
  trademarkParams.logoUrl = row.logoUrl;
  // 添加id
  trademarkParams.id = row.id;
  dialogFormVisible.value = true;
};

// 删除品牌按钮回调
const removeTrademark = async (id: number) => {
  const res = await reqDeleteTrademark(id);
  if (res.code === 200) {
    ElMessage.success("删除成功");
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1
    );
  } else {
    ElMessage.error("删除失败");
  }
};

// 对话框取消按钮回调
const cancel = () => {
  dialogFormVisible.value = false;
};

// 对话框确定按钮回调
const confirm = async () => {
  // 发送请求之前 先进行表单校验
  const resCheck = await formRef.value.validate();
  const res = await reqAddOrUpdateTrademark(trademarkParams);

  // 添加||修改
  if (res.code === 200) {
    // 添加成功 关闭对话框 弹出提示信息
    dialogFormVisible.value = false;
    ElMessage.success(trademarkParams.id ? "修改成功" : "添加成功");
    // 重新获取数据
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    // 添加失败
    ElMessage.error(trademarkParams.id ? "修改失败" : "添加失败");
    dialogFormVisible.value = false;
  }
};

// 上传图片组件->上传图片之前的钩子 可以限制文件类型
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  console.log(rawFile);
  // 要求:文件类型:png,jpg,jpeg,gif 4M
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpg" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "上传图片大小不能超过4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传图片只能是png,jpg,jpeg,gif格式的图片",
    });
  }
};

// 图片上传成功后的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // response: 后台返回的数据
  // uploadFile: 上传的文件对象
  trademarkParams.logoUrl = response.data;
  // 图片上传成功 清除错误信息
  formRef.value.clearValidate("logoUrl");
};

// 品牌自定义校验规则
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.length < 2 || value.length > 10) {
    return callback(new Error("品牌名称长度必须在2-10位之间"));
  } else {
    return callback();
  }
};

const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (typeof value !== "string" || value.trim().length === 0) {
    return callback(new Error("请上传品牌LOGO"));
  } else {
    return callback();
  }
};

// 表单校验规则对象
const rules = {
  tmName: [
    {
      required: true,
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      trigger: "blur",
      validator: validatorLogoUrl,
    },
  ],
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
